package com.yueqian.exception;

import java.util.Arrays;

public class Queue {

    private Object[] items;

    public Queue(int size) {
        // [b, null, null, null,null ]
        items = new Object[size];
    }

    /**
     * 放入队列尾
     */
    public void put(Object item) {
        for (int i = 0; i < items.length; i++) {
            if (items[i] == null) {
                items[i] = item;
                return;
            }
        }
        //队列满，抛出满队列异常
        throw new QueueFullException();
    }

    /**
     * 弹出队列头
     */
    public Object get() throws QueueEmptyException {
        if (items[0] == null) {
            //队列满，抛出满队列异常
            throw new QueueEmptyException();
        }
        Object result = items[0];
        //将后续的内容向前移动
        for (int i = 1; i < items.length; i++) {
            //将队尾置空
            if (items[i] == null) {
                items[i - 1] = null;
                break;
            }
            items[i - 1] = items[i];
            //满队，将最后一个元素置空
            if (i == items.length - 1 && items[i] != null) {
                items[i] = null;
            }
        }

        return result;
    }

    @Override
    public String toString() {
        return "Queue" + Arrays.toString(items);
    }
}
